package repository

import (
	"gorm.io/gorm"
	"shop-bean/model"
	"shop-bean/vo"
	"shop-common/utils/queryWrapper"
)

type IStoreCategoryRepository interface {
	FindById(db *gorm.DB, categoryId uint, _type uint8) (row *model.StoreCategory, err error)
	FindJoin(db *gorm.DB, _type uint8, categoryId *uint) ([]*vo.StoreCategoryVO, error)
	FindSimple(db *gorm.DB, _type uint8) ([]*model.StoreCategory, error)
	FindOne(db *gorm.DB, pair *queryWrapper.WherePair) (*model.StoreCategory, error)
	Updates(db *gorm.DB, categoryId uint, columns map[string]interface{}) error
}

type StoreCategoryRepository struct {
}

func NewStoreCategoryRepository() IStoreCategoryRepository {
	return &StoreCategoryRepository{}
}

func (r *StoreCategoryRepository) FindJoin(db *gorm.DB, _type uint8, categoryId *uint) (list []*vo.StoreCategoryVO, err error) {
	return list, leftJoinAttachment(db, _type, categoryId != nil, categoryId).Find(&list).Error
}

func (r *StoreCategoryRepository) FindById(db *gorm.DB, categoryId uint, _type uint8) (row *model.StoreCategory, err error) {
	return row, db.Model(&model.StoreCategory{}).
		Where("category_id = ?", categoryId).Where("status = 2").Where("type = ?", _type).
		First(&row).Error
}

func leftJoinAttachment(db *gorm.DB, _type uint8, isIcon bool, categoryId *uint) *gorm.DB {
	query := "LEFT JOIN tz_attachment ta ON sc.icon_id = ta.att_id"
	if isIcon {
		query += " or sc.icon_id = ta.att_id"
	}
	tx := db.Table("tz_store_category sc").
		Select("sc.category_id, sc.parent_id, sc.category_name, sc.big_id, sc.icon_id, sc.type, sc.`status`, ta.att_id, ta.`name`, sc.seq, ta.image_type, ta.att_dir").
		Joins(query).Where("sc.deleted_at is null").Where("sc.`status` = 2").Where("sc.`type` = ?", _type)

	if categoryId != nil {
		tx = tx.Where("sc.category_id = ?", categoryId)
	} else {
		tx = tx.Order("sc.seq desc").Order("sc.updated_at desc")
	}
	return tx
}

func (r *StoreCategoryRepository) FindSimple(db *gorm.DB, _type uint8) (list []*model.StoreCategory, err error) {
	return list, db.Model(&model.StoreCategory{}).Where("type = ?", _type).Where("status = 2").Find(&list).Error
}

func (r *StoreCategoryRepository) FindOne(db *gorm.DB, pair *queryWrapper.WherePair) (category *model.StoreCategory, err error) {
	return category, queryWrapper.ReuseWherePair(db.Model(&model.StoreCategory{}), pair).First(&category).Error
}

func (r *StoreCategoryRepository) Updates(db *gorm.DB, categoryId uint, columns map[string]interface{}) error {
	return db.Model(&model.StoreCategory{}).Where("category_id = ?", categoryId).Updates(columns).Error
}
